'use client'

import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { useParams, useRouter } from 'next/navigation'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import Loading from '@/components/Loading'
import useRequest from '@/utils/request'

const FormSchema = z.object({
  brand: z
    .string()
    .min(1, {
      message: 'Please enter your brand name (between 1 and 50 characters).',
    })
    .max(50, {
      message: 'Please enter your brand name (between 1 and 50 characters).',
    }),
  url: z
    .string()
    .min(3, {
      message: 'Please enter your site url (ex: domain.com).',
    })
    .max(50, {
      message: 'Please enter your site url (ex: domain.com).',
    }),
  desc: z
    .string()
    .min(15, {
      message: 'Please describe the essence of your project/business (between 15 and 100 characters).',
    })
    .max(1000, {
      message: 'Please describe the essence of your project/business (between 15 and 100 characters).',
    }),
})

export default function ProjectsEdit() {
  const [loading, setLoading] = useState(true)
  const [id, setId] = useState(0)
  const params = useParams()
  const router = useRouter()
  const { toast } = useToast()
  const request = useRequest()

  const fetchData = async () => {
    const res = await request.get(`red_growth/project?id=${params.id}`)
    setId(res.data.id)
    setLoading(false)
    return {
      brand: res.data.brand,
      url: res.data.url,
      desc: res.data.desc,
    }
  }

  const form = useForm({
    resolver: zodResolver(FormSchema),
    defaultValues: async () => await fetchData(),
  })

  async function onSubmit(data) {
    try {
      const response = await request.put('red_growth/project', { ...data, id })
      toast({
        title: `Project '${data.brand}' has been updated.`,
        description: 'It may take up to 10 minutes for changes to become active.',
      })
      router.push('/projects')
    } catch (error) {
      console.error('Error submitting form:', error)
    }
  }

  if (loading) {
    return <Loading />
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
        <FormField
          control={form.control}
          name="brand"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Brand name</FormLabel>
              <FormControl>
                <Input placeholder="ex: OpenAI" {...field} />
              </FormControl>
              <FormDescription></FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="url"
          render={({ field }) => (
            <FormItem>
              <FormLabel>URL</FormLabel>
              <FormControl>
                <Input placeholder="ex: openai.com" {...field} />
              </FormControl>
              <FormDescription></FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="desc"
          render={({ field }) => (
            <FormItem>
              <FormLabel>A short description of your project</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="ex: OpenAI is an AI research and deployment company. Our mission is to ensure that artificial general intelligence benefits all of humanity."
                  {...field}
                />
              </FormControl>
              <FormDescription>
                Based on this description, the AI selects references for which it can recommend your project. Therefore,
                it is important to briefly describe the essence of your project/business.
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit">Update</Button>
      </form>
    </Form>
  )
}
